<template>
  <div class="card" style="height: 80vh">
   <div class="font-semibold text-xl mb-4">资产</div>
    <Button class="mr-2" type="button" icon="pi pi-plus" label="新增"
            @click="() => {visible.createModal = true;}"/>


    <DataView :value="schemaList" layout="grid">
      <template #grid="slotProps">
        <ScrollPanel style="width: 100%; height: 63vh">
          <div class="grid sm:grid-cols-1 md:grid-cols-3 lg:grid-cols-5 xl:grid-cols-6" id='move'>
            <div v-for="(item, index) in slotProps.items" :key="index"
                 class="cursor-pointer p-2">
              <div class='surface-card rounded p-3 hover-box flex flex-col items-center' id='move-parent'
                   @click="() => router.push({name: 'instance', query: {schema_id: item.schema_id}})">
<!--                <i class="pi pi-bars move-icon drag-handle" style="font-size: 1rem"></i>-->
                <div class='flex align-items-center m-2'>
                  <div style="word-break: break-all;height: 1rem">{{ item.schema_id }}</div>
                </div>
                <div class='flex align-items-center m-2'>
                  <div style="word-break: break-all;height: 1rem">{{ item.name }}</div>
                </div>
                <div>
                  <Button icon="pi pi-pen-to-square" severity="secondary" rounded text size="large"
                          class='m-2'
                          @click=" (e) =>{e.stopPropagation();openSchemaForm(item)}"/>
                  <Button icon="pi pi-ellipsis-h" text rounded
                          @click="(e) => {e.stopPropagation();MoreToggle(e, item)}"/>
                </div>
              </div>
            </div>
          </div>
        </ScrollPanel>
      </template>
    </DataView>
    <Menu ref="moreMenu" :model="moreItem" :popup="true">
      <template #item="{ item, props }">
        <a v-ripple class="flex items-center" v-bind="props.action" @click="() => requireConfirmation()">
          <span :class="item.icon" class="text-red-400"/>
          <span class="text-red-400">{{ item.label }}</span>
        </a>
      </template>
    </Menu>

    <Dialog
        header='新建类型'
        modal
        v-model:visible="visible.createModal"
    >
      <form @submit.prevent='submitSchema'>
        <div class="mt-4 flex items-center gap-4">
          <label for="schemaId" class="text-sm font-semibold text-right w-16">类型ID</label>
          <div class="flex-1">
            <InputText id="schemaId" v-model="schemaId" class="w-full" autocomplete="off"/>
            <small class="text-red-500">{{ errorsSchama.schema_id }}</small>
          </div>
        </div>
        <div class="mt-4 flex items-center gap-4">
          <label for="schemaName" class="text-sm font-semibold text-right w-16">类型名称</label>
          <div class="flex-1">
            <InputText id="schemaName" v-model="schemaName" class="w-full" autocomplete="off"/>
            <small class="text-red-500">{{ errorsSchama.name }}</small>
          </div>
        </div>
        <div class="mt-4 flex items-center gap-4">
          <label for="schemaDesc" class="text-sm font-semibold text-right w-16">描述</label>
          <div class="flex-1">
            <InputText id="schemaDesc" v-model="schemaDesc" class="w-full" autocomplete="off"/>
            <small class="text-red-500">{{ errorsSchama.desc }}</small>
          </div>
        </div>

        <Button label="新增属性" @click="createFieldEvent" class="mt-3 mb-3"/>

        <DataTable :value="schemaFields" tableStyle="min-width: 50rem">
          <Column field="name" header="属性ID">
            <template #body="{ data, field }">
              <InputText v-if="data._editor" id="field_id" v-model="data.field_id" class="flex-auto"
                         autocomplete="off"/>
              <div v-else>{{ data.field_id }}</div>
            </template>
          </Column>
          <Column field="name" header="属性名称">
            <template #body="{ data, field }">
              <InputText v-if="data._editor" id="name" v-model="data.name" class="flex-auto"
                         autocomplete="off"/>
              <div v-else>{{ data.name }}</div>
            </template>
          </Column>
          <Column field="name" header="属性类型">
            <template #body="{ data, field }">
              <div v-if="!data._editor">
                <div v-if="data.meta.type === 'types.String'">字符串</div>
                <div v-else-if="data.meta.type === 'types.Int'">整数</div>
                <div v-else-if="data.meta.type === 'types.Float'">浮点数</div>
                <div v-else>未知</div>
              </div>

              <Select v-else v-model="data.meta.type" :options="fieldTypes" optionLabel="label"
                      optionValue="value"
                      placeholder="Select a City"
                      class="w-full md:w-56"/>
            </template>
          </Column>
          <Column field="meta" header="隐藏">
            <template #body="{ data, field }">
              <ToggleSwitch v-model="data.meta.hidden" :disabled="!data._editor"/>
            </template>
          </Column>
          <Column field="meta" header="描述">
            <template #body="{ data, field }">
              <InputText v-if="data._editor" id="desc" v-model="data.desc" class="flex-auto"
                         autocomplete="off"/>
              <div v-else>{{ data.desc }}</div>
            </template>
          </Column>
          <Column field="action" header="操作">
            <template #body="slotProps">
              <div v-if="slotProps.data._editor">
                <i class="pi pi-check"
                   @click="() => udpateFied(slotProps.data)"></i>
                <i v-if="slotProps.data._edit" class="pi pi-minus ml-3"
                   @click="() =>  {slotProps.data._edit = false;slotProps.data._editor = false}"></i>
                <i v-else class="pi pi-minus ml-3"

                   @click="() =>  schemaFields.splice(slotProps.index, 1)"></i>
              </div>

              <div v-else>
                <i class="pi pi-pencil"
                   @click="() => {schemaFields[slotProps.index]._editor = true;schemaFields[slotProps.index]._edit = true}"></i>
                <i class="pi pi-trash ml-3"
                   @click="() =>  schemaFields.splice(slotProps.index, 1)"></i>
              </div>
            </template>
          </Column>
        </DataTable>
        <div class="flex justify-end gap-2  mt-3">
          <Button type="button" label="取消" severity="secondary"
                  @click="() => {visible.createModal = false; resetFormSchema()}"></Button>
          <Button type="submit" label="提交"></Button>
        </div>
      </form>
    </Dialog>
  </div>
  <ConfirmDialog></ConfirmDialog>
</template>

<script setup>
import {computed, reactive, ref,} from "vue";
import router from "@/router.js";
import {usePagination} from "vue-request";
import {
  ApiFieldList,
  ApiSchemalList,
  ApiFieldCreate,
  ApiSchemaCreate,
  ApiSchemaUpdate,
  ApiSchemaDelete
} from "@/api/cmdb.js";
import * as yup from "yup";
import {useForm} from "vee-validate";
import {useRequest} from 'ahooks-vue';
import ToggleSwitch from 'primevue/toggleswitch';
import Select from 'primevue/select';
import {useToast} from "primevue/usetoast";
import Menu from 'primevue/menu';
import {useConfirm} from "primevue/useconfirm";
import ConfirmDialog from 'primevue/confirmdialog';

const toast = useToast();
const confirm = useConfirm();

const position = ref('bottom');
const align = ref('end');
const modelCreateFormRef = ref();
const data = ref([])
const moreMenu = ref();
const loading = reactive({
  create: false
})
const visible = reactive({
  createModal: false
})
const tagState = reactive({
  index: 'all',
  options: [{label: '全部', value: 'all'}]
});
const modelCreateForm = reactive({
  id: '',
  name: '',
  desc: '',
});

const getContainer = () => {
  return document.getElementById("modalBox");
};


const modalTitleRef = ref(null);
const startX = ref(0);
const startY = ref(0);
const startedDrag = ref(false);
const transformX = ref(0);
const transformY = ref(0);
const preTransformX = ref(0);
const preTransformY = ref(0);
const dragRect = ref({
  left: 0,
  right: 0,
  top: 0,
  bottom: 0,
});

const fieldTypes = [
  {
    'value': 'types.String',
    'label': '字符串',
  },
  {
    'value': 'types.Int',
    'label': '整数',
  },
  {
    'value': 'types.Float',
    'label': '浮点数',
  }
]

const moreItem = ref([
  {
    label: '删除',
    icon: 'pi pi-trash',
  }
])

const {
  data: schemaData,
  run: modelRun,
  loading: modelLoading,
  refresh: schemaRefresh,
  current,
  pageSize,
} = usePagination(ApiSchemalList, {
  pagination: {
    currentKey: 'page',
    pageSizeKey: 'page_size',
    totalKey: 'data.total',
  },
});
const schemaList = computed(() => schemaData.value?.data.list || []);
const total = computed(() => schemaData.value?.data.total || []);

function screenPageSize() {
  if (window.innerWidth > 1500) {
    return 21
  } else {
    return 15
  }
}

const {data: fieldData, loading: fieldLoading, run: fieldRun} = useRequest(ApiFieldList, {
  manual: true,
//    onSuccess: e => {
//        formState.value = e.data.detail
//    },
})

const fieldList = computed(() => fieldData.value?.data.list || []);
const onOk = async () => {
  await modelCreateFormRef.value.validateFields()
  const result = await ApiModelCreate({...modelCreateForm})
  if (result.code === 0) {
    message.success(result.msg);
    visible.createModal = false
    modelRun()
  } else {
    message.error(result.msg);
  }
  modelCreateFormRef.value.resetFields()
};

const fields = []

let SchemaVal = yup.object().shape({
  schema_id: yup.string().max(20, '字符长度过多').required('请输入资产类型ID'),
  name: yup.string().max(20, '字符长度过多').required('请输入资产类型名称'),
  desc: yup.string().max(255, '字符长度过多').default(''),
  fields: yup.array()
});

const {
  defineField: defineFieldSchema,
  handleSubmit: handleSubmitSchema,
  resetForm: resetFormSchema,
  errors: errorsSchama,
  setValues: setValuesSchema
} = useForm({
  validationSchema: SchemaVal,
  initialValues: {
    fields: []
  }
});

const [schemaId] = defineFieldSchema('schema_id');
const [schemaName] = defineFieldSchema('name');
const [schemaDesc] = defineFieldSchema('desc');
const [schemaFields] = defineFieldSchema('fields');

const submitSchema = handleSubmitSchema(async (values) => {
  console.log(values)
  let result;
  if (values.update) {
    result = await ApiSchemaUpdate(values)
  } else {
    result = await ApiSchemaCreate(values)
  }
  if (result.code === 0) {
    toast.add({severity: 'success', summary: '成功', detail: result.msg, life: 3000});
    visible.createModal = false
    schemaRefresh()
  } else {
    toast.add({severity: 'error', summary: '错误', detail: result.msg, life: 3000});
    return
  }
  setValuesSchema({id: null})
  resetFormSchema()
});

function createFieldEvent() {
  schemaFields.value.push({
    _editor: true,
    field_id: '',
    name: '',
    meta: {
      type: 'types.String',
      hidden: false
    }
  })
}

const udpateFied = async (data) => {
  data._editor = false
}

const MoreToggle = (event, data) => {
  moreMenu.value.toggle(event);
  moreMenu.value.data = data
}

const requireConfirmation = () => {
  const data = moreMenu.value.data
  confirm.require({
    message: '确定要删除类型 ' + data.name + ' 吗？',
    header: '删除提示',
    icon: 'pi pi-info-circle',
    rejectLabel: '取消',
    rejectProps: {
      label: '取消',
      severity: 'secondary',
      outlined: true
    },
    acceptProps: {
      label: '删除',
      severity: 'danger'
    },
    accept: async () => {
      const result = await ApiSchemaDelete(data.id)
      if (result.code === 0) {
        toast.add({severity: 'success', summary: '删除成功', detail: result.msg, life: 3000});
        schemaRefresh()
      } else {
        toast.add({severity: 'danger', summary: '错误', detail: result.msg, life: 3000});
      }
    },
  });
};

const openSchemaForm = async (data) => {
  const result = await fieldRun(data.id)
  visible.createModal = true;
  data.fields = result.data.list
  data['update'] = true
  setValuesSchema(data);
}

const instanceImport = async (values) => {
  // 构造 multipart/form-data 数据
  const formData = new FormData();
  formData.append('schema_id', this.schema_id);
  formData.append('quit', this.quit);
  formData.append('file', this.file);
}
</script>

<style scoped>
</style>